<?php
/**
 * 保存微信登录配置
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');

// 获取POST数据
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data) {
    echo json_encode(['success' => false, 'message' => '无效的请求数据']);
    exit;
}

// 读取现有配置
$configFile = __DIR__ . '/../../config.php';
$config = include $configFile;

// 更新微信配置
if (!isset($config['plugins'])) {
    $config['plugins'] = [];
}

if (!isset($config['plugins']['wechat'])) {
    $config['plugins']['wechat'] = [];
}

// 保留enabled状态
$enabled = $config['plugins']['wechat']['enabled'] ?? false;

$config['plugins']['wechat'] = [
    'enabled' => $enabled,
    'app_id' => $data['app_id'] ?? '',
    'app_secret' => $data['app_secret'] ?? '',
    'redirect_uri' => $data['redirect_uri'] ?? ''
];

// 写入配置文件
$configContent = "<?php\n/**\n * 氚云API管理系统配置文件\n * Alyr.net 企业级配置管理\n */\n\nreturn " . var_export($config, true) . ";\n";

if (file_put_contents($configFile, $configContent)) {
    echo json_encode(['success' => true, 'message' => '配置保存成功']);
} else {
    echo json_encode(['success' => false, 'message' => '配置文件写入失败']);
}
